package com.shushan.mixedexam.englishwords;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.shushan.base.BaseFragment;
import com.shushan.base.Constants;
import com.shushan.mixedexam.BaseExamFragment;
import com.shushan.mixedexam.OnAnswerSelectListener;
import com.shushan.mixedexam.bean.MutiExerciseBean;
import com.shushan.mixedexam.englishwords.adapter.WordCharsGvAdapter;
import com.shushan.shushanbao.R;
import com.shushan.ui.TextViewBox;
import com.shushan.util.DensityUtil;
import com.shushan.util.DownloadUtil;
import com.shushan.util.ExamAudioPlayUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @ClassName: EnglishWordsExam3Fragment
 * @Desciption: //单词练习题型3 fragment
 * @author: zhangshihao
 * @date: 2018-07-26
 */
public class EnglishWordsExam3Fragment extends BaseExamFragment implements AdapterView.OnItemClickListener, View.OnClickListener {

    private static final String TAG = EnglishWordsExam3Fragment.class.getSimpleName();

    private View contentView;
    private GridView gridView;
    private LinearLayout llEditContainer;
    private TextView tvWord;
    private ImageView ivTrumpet;

    private AnimationDrawable playAnim;
    private RelativeLayout rlBoxContainer;
    private TextView tvRightAnswer;

    private String word = "";//正确的单词
    private int dividerWidth = 4;//空白框间距：dp
    private List<Character> charList;//给用户提供的所有字符
    private List<TextViewBox> boxes = new ArrayList<>();//空白框列表
    private int currentBlankIndex = 0;
    private List<View> invisibleViewList = new ArrayList<>();
    private Context context;
    private boolean isOnlyDisplay = false;
    private int examIndex = 0;
    private MutiExerciseBean exerciseBean;
    private OnAnswerSelectListener onAnswerSelectListener;
    private boolean isAnswered = false;//用户是否回答完毕
    private static final int MAX_WORD_INDEX = 15;

    public static EnglishWordsExam3Fragment newInstance(Context context, boolean isOnlyDisplay, int examIndex, MutiExerciseBean exerciseBean) {
        EnglishWordsExam3Fragment exam3Fragment = new EnglishWordsExam3Fragment();
        exam3Fragment.setContext(context);
        exam3Fragment.setOnlyDisplay(isOnlyDisplay);
        exam3Fragment.setExamIndex(examIndex);
        exam3Fragment.setExerciseBean(exerciseBean);

        return exam3Fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_english_words_exam_3, null, false);

            initView();

            initData();
        }
        return contentView;
    }

    private void initView() {
        gridView = contentView.findViewById(R.id.grid_view);
        llEditContainer = contentView.findViewById(R.id.ll_text_container);
        tvWord = contentView.findViewById(R.id.tv_word);
        ivTrumpet = contentView.findViewById(R.id.iv_trumpet);
        ivTrumpet.setOnClickListener(this);
        ivTrumpet.setImageResource(R.drawable.anim_audio_play);
        playAnim = (AnimationDrawable) ivTrumpet.getDrawable();
        rlBoxContainer = contentView.findViewById(R.id.rl_box_container);
        tvRightAnswer = contentView.findViewById(R.id.tv_right_selector);
        if(!Constants.isForEditors){
            tvRightAnswer.setVisibility(View.GONE);
        }
    }

    private void initData() {
        if (exerciseBean == null) {
            return;
        }

        tvRightAnswer.setText(exerciseBean.answer);

        tvWord.setText(exerciseBean.exercises_content);
        int screenWidth = DensityUtil.getScreenWidth(getActivity());
        word = exerciseBean.answer;
        int wordLength = word.length();
        float boxWidth = 42.5f;
        while (isWidthBigerThanScreen(boxWidth, wordLength, screenWidth)) {
            boxWidth--;
        }
        for (int i = 0; i < wordLength; i++) {
            TextViewBox box = new TextViewBox(context);
            box.setIndex(i);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtil.dip2px(context, boxWidth), DensityUtil.dip2px(context, boxWidth));
            layoutParams.leftMargin = DensityUtil.dip2px(context, dividerWidth);
            box.setLayoutParams(layoutParams);
            llEditContainer.addView(box);
            boxes.add(box);
        }
        if (isOnlyDisplay) {
            rlBoxContainer.setVisibility(View.GONE);
            if(TextUtils.isEmpty(exerciseBean.my_option)) {
                fillBoxes(exerciseBean.my_answer_id_str);
            }else{
                fillBoxes(exerciseBean.my_option);
            }
        } else {
            List<Character> disturbChars = new ArrayList<>();//干扰字符
            for (int i = 0; i < MAX_WORD_INDEX - wordLength; i++) {
                disturbChars.add(i, (char) (Math.random() * 26 + 'a'));//随机添加英文字母
            }
            List<Character> rightAnswerChars = new ArrayList<>();//正确答案字符列表
            for (int i = 0; i < word.length(); i++) {
                rightAnswerChars.add(word.charAt(i));
            }
            charList = new ArrayList<>();//所有字符列表
            //预填充15个随机字符
            for(int i=0;i<MAX_WORD_INDEX;i++){
                charList.add((char) (Math.random() * 26 + 'a'));//随机添加英文字母
            }
            List<Integer> rightAnswerIndex = new ArrayList<>();//正确答案字符所在序号列表
            int count = 0;
            Random rand = new Random();
            while (count < rightAnswerChars.size()) {
                int index = rand.nextInt(MAX_WORD_INDEX);
                if (index == 4) {
                    continue;
                }
                boolean isExist = false;
                for (int i = 0; i < rightAnswerIndex.size(); i++) {
                    if ((i < MAX_WORD_INDEX-1) && (index == rightAnswerIndex.get(i))) {
                        isExist = true;
                    }
                }
                if (!isExist) {
                    rightAnswerIndex.add(index);
                    count++;
                }
            }
            for (int i = 0; i < rightAnswerIndex.size(); i++) {
                charList.set(rightAnswerIndex.get(i), rightAnswerChars.get(i));
            }
            int index = 0;
            for (int j = 0; j < disturbChars.size(); j++) {
                boolean isConflict;
                do {
                    isConflict = false;
                    for (int i = 0; i < rightAnswerIndex.size(); i++) {
                        if (index == rightAnswerIndex.get(i)) {
                            index++;
                            isConflict = true;
                        }
                    }
                }while (isConflict);
                charList.set(index, disturbChars.get(j));
            }
            charList.set(4, '_');
            WordCharsGvAdapter adapter = new WordCharsGvAdapter(context, charList);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(this);
        }
    }

    private void fillBoxes(String myAnswer) {
        for (int i = 0; i < boxes.size(); i++) {
            TextViewBox box = boxes.get(i);
            if(!TextUtils.isEmpty(myAnswer) && myAnswer.length() > i){
                box.setText(String.valueOf(myAnswer.charAt(i)));
            }
        }
    }

    private boolean isWidthBigerThanScreen(float boxWidth, int wordLength, int screenWidth) {
        if (DensityUtil.dip2px(context, (boxWidth * wordLength)) + DensityUtil.dip2px(context, (wordLength + 1) * dividerWidth) > screenWidth) {
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_trumpet:
                if (exerciseBean == null) {
                    break;
                }
                ExamAudioPlayUtil.playAudio(DownloadUtil.getEnglishWordsStudyAudioPath(exerciseBean.outline_detail_id, exerciseBean.id), playAnim);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position != 4) {
            if (currentBlankIndex == word.length()) {
                return;
            }
            fillBlank(parent, view, position, id);
        } else {
            if (invisibleViewList.size() == 0) {
                return;
            }
            deleteBlank(parent, view, position, id);
        }
    }

    private void fillBlank(AdapterView<?> parent, View view, int position, long id) {
        boxes.get(currentBlankIndex).setText(String.valueOf(charList.get(position)));
        currentBlankIndex++;
        view.setVisibility(View.INVISIBLE);
        invisibleViewList.add(view);
        if (currentBlankIndex == word.length()) {
            exerciseBean.my_option = getAnswerStr();
            if(onAnswerSelectListener != null) {
                onAnswerSelectListener.onAnswerSelect(examIndex, getAnswerStr().equalsIgnoreCase(exerciseBean.answer));
                isAnswered = true;
            }
        }
    }

    private String getAnswerStr() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < boxes.size(); i++) {
            sb.append(boxes.get(i).getText());
        }
        return sb.toString();
    }

    private void deleteBlank(AdapterView<?> parent, View view, int position, long id) {
        if(isAnswered){
            return;
        }
        int lastIndex = invisibleViewList.size() - 1;
        boxes.get(currentBlankIndex - 1).setText("");
        invisibleViewList.get(lastIndex).setVisibility(View.VISIBLE);
        invisibleViewList.remove(lastIndex);
        currentBlankIndex--;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public OnAnswerSelectListener getOnAnswerSelectListener() {
        return onAnswerSelectListener;
    }

    public void setOnAnswerSelectListener(OnAnswerSelectListener onAnswerSelectListener) {
        this.onAnswerSelectListener = onAnswerSelectListener;
    }

    public boolean isOnlyDisplay() {
        return isOnlyDisplay;
    }

    public void setOnlyDisplay(boolean onlyDisplay) {
        isOnlyDisplay = onlyDisplay;
    }

    public int getExamIndex() {
        return examIndex;
    }

    public void setExamIndex(int examIndex) {
        this.examIndex = examIndex;
    }

    public MutiExerciseBean getExerciseBean() {
        return exerciseBean;
    }

    public void setExerciseBean(MutiExerciseBean exerciseBean) {
        this.exerciseBean = exerciseBean;
    }

    public AnimationDrawable getPlayAnim() {
        return playAnim;
    }

    public String getAudioPath(MutiExerciseBean bean){
        if(bean == null){
            return "";
        }
        return DownloadUtil.getEnglishWordsStudyAudioPath(bean.outline_detail_id, bean.id);
    }

}
